package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /**
     *
     * @param file 这个参数要与前端定义的一致
     * @return
     */
    @Operation(summary = "专辑封面上传")
    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file){
        //返回值应该是文件的存储地址
        String url = "";
        //调用minio的api上传文件到minion中
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            //创建一个minio的客户端，并配置minion的地址和access key and secret key
            /**
             * 不能显示的设置，放到了配文件中，通过MinioConstantProperties类获得
             */
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(),
                                    minioConstantProperties.getSecreKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            //看看有没有这个桶
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder()
                            .bucket(minioConstantProperties.getBucketName())
                            .build());
            //没有就创建
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioConstantProperties.getBucketName())
                        .build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            /*minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(minioConstantProperties.getBucketName())
                            .object("asiaphotos-2015.zip")
                            .filename("/home/user/Photos/asiaphotos.zip")
                            .build());*/

            // Upload known sized input stream.
            //拼接文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+
                    file.getOriginalFilename().substring(
                            file.getOriginalFilename().lastIndexOf(".")
                    );

            System.out.println(fileName);
            //上传一个知道大下小的文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConstantProperties.getBucketName())
                            //对象名称:应该是uuid+文件的后缀
                            .object(fileName)
                            //设置上传文件的inputStream和大小
                            .stream(file.getInputStream(),file.getSize(), -1)
                            //文件的类型
                            .contentType(file.getContentType())
                            .build());

            url = minioConstantProperties.getEndpointUrl()+"/"
                    +minioConstantProperties.getBucketName()+"/"
                    +fileName;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
//            System.out.println("HTTP trace: " + e.httpTrace());
        }

        return Result.ok(url);

    }

}
